import {
	mapMutations
} from 'vuex'
export default {
	...mapMutations(['upRefreshFlag']),
	back() {
		let that = this
		this.$toast.confirm({
			content: `是否退出编辑？`,
			confirmText: '确认',
			callback: result => {
				if (result) {
					const pages = getCurrentPages();
					if (pages.length === 2) {
						uni.navigateBack({
							delta: 1
						});
					} else if (pages.length === 1) {
						uni.switchTab({
							url: '/pages/index/index',
						})
					} else {
						uni.navigateBack({
							delta: 1
						});
					}
				}
			}
		})
	},
	changeMode(e) {
		this.type = e
		this.showMode = false;
	},
	// 选择好友
	selectFriend(friends) {
		this.mentionedFriends = friends; // 添加到提到的好友列表
		this.$refs.userPop.close();
	},
	watchChange(e) {
		this.watchIndex = e.detail.value;
		if (this.watchIndex == 2) {
			this.$refs.userPop.show();
		} else {
			this.mentionedFriends = []
		}
		this.formData.visibilityType = this.watchType[e.detail.value].id
	},
	getData(id) {
		let that = this
		that.$httpRequest.request({
			that: that,
			method: 'get',
			url: 'wechat/getInformationDetail',
			params: {
				id: id
			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					// that.detail = res.data
					console.log(res.data)
					that.formData = res.data;
					that.topicList = res.data.topics.split(',').map((item) => {
						return Number(item)
					});
					// that.wordList = res.data.filesList;
					res.data.filesList.forEach(item => {
						that.addProperties(item)
					})
					that.changeMode(res.data.type)
				}
			}
		})
	},
	handlerUpload() {
		let that = this;
		let tempObj = {}
		if (this.wordList.length > 15) {
			this.$toast.msg('最多数量为15', {
				icon: 1
			})
			return false
		}
		uni.showActionSheet({
			itemList: ['照片', '视频'],
			success: function(res) {
				if (res.tapIndex == 0) {
					//上传照片
					that.$httpRequest.handlerUploadPic(res => {
						if (res.code === that.$httpConfig.SUCCESS_CODE) {
							console.log(res, "完成上传")
							res.tempNameArray.forEach((item, index) => {
								if (item.indexOf(res.data
										.fileOriginName) > 0) {
									tempObj[index] = res.data
								}
								// #ifdef  H5
								tempObj[index] = res.data
								// #endif

							})
							console.log("临时数组=========", tempObj)
							//多照片
							var arr = []
							for (let key in tempObj) {
								// console.log(key, tempObj[key])
								arr.push(tempObj[key])
							}
							// console.log("临时数组=========", tempObj)
							// that.wordList = []
							that.wordList = that.wordList.concat(arr)

							// console.log("去空值后",that.wordList)
							that.wordList = that.unique(that.wordList)
							that.wordList = that.trimSpace(that.wordList)
							console.log("wordList=========", that.wordList)
							var newlist = that.wordList.map((item, index) => {
								if (item) {
									return item = item.id
								}

							})
							that.formData.files = newlist.join(',')

						}
					});
				} else {
					//上传视频
					that.$httpRequest.handlerUploadVideo(res => {
						if (res.code === that.$httpConfig.SUCCESS_CODE) {
							//多照片
							that.wordList.push(res.data)
							var newlist = that.wordList.map((item, index) => {
								return item = item.id
							})
							that.formData.files = newlist.join(',')
						}

					})

				}
				console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
			},
			fail: function(res) {
				console.log(res.errMsg);
			}
		});

	},
	_previewImage(image) {
		var imgArr = [];
		imgArr.push(image);
		//预览图片
		uni.previewImage({
			urls: imgArr,
			current: imgArr[0]
		});
	},
	//删除照片
	del(index) {
		this.wordList.splice(index, 1)
		var newlist = this.wordList.map((item, index) => {
			return item = item.id
		})
		this.formData.files = newlist.join(',')
	},
	toPreview() {
		if (this.type == 2) {
			if (!this.formData.price) {
				this.$toast.msg('请输入价格', {
					icon: 1
				})
				return false
			}

		}
		if (!this.formData.title) {
			this.$toast.msg('请输入标题', {
				icon: 1
			})
			return false
		}
		if (!this.formData.content) {
			this.$toast.msg('请输入正文', {
				icon: 1
			})
			return false
		}
		if (!this.formData.shippingPrice && this.type == 2) {
			this.$toast.msg('请输入运费', {
				icon: 1
			})
			return false
		}

		if (this.imageList.length < 1) {
			this.$toast.msg('请上传图片或者视频', {
				icon: 1
			})
			return false
		}
		let data = this.formData;
		data.filesList = this.imageList.slice().sort((a, b) => a.index - b.index);
		data.topicList = this.topic.filter(item => this.topicList.includes(item.id));
		uni.setStorageSync('preview', JSON.stringify(data));
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/index/preview'
			})
		}, 50)

	},
	unique(list) {
		let result = {};
		let finalResult = [];
		for (let i = 0; i < list.length; i++) {
			if (list[i]) {
				result[list[i].id] = list[i];
			}

			//因为list[i].id不能重复,达到去重效果,且这里必须知晓"id"或是其他键名
		}
		//现在result内部都是不重复的对象了，只需要将其键值取出来转为数组即可
		for (let item in result) {
			finalResult.push(result[item]);
		}
		//console.log(finalResult);[{id:"羽根",artist:"air"},{name:"id",artist:"周杰伦"}]
		return finalResult;
	},
	trimSpace(array) {
		for (var i = 0; i < array.length; i++) {
			if (array[i] == " " || array[i] == null || typeof(array[i]) == "undefined") {
				array.splice(i, 1);
				i = i - 1;

			}
		}
		return array;
	},
	getLocation() {
		let that = this
		uni.getLocation({
			type: 'gcj02', //gcj02,
			geocode: true, //设置该参数为true可直接获取经纬度及城市信息
			success: res => {
				console.log(res)
				that.formData.lal = res.latitude + ',' + res.longitude
				that.getCurrentCity(res.latitude, res.longitude)
			},
			fail: res => {
				// console.log(res)
				if (res.errMsg === 'getLocation:fail auth deny') {
					that.$toast.confirm({
						content: '为了更好服务。请授权获取您当前的地理位置',
						confirmText: '去设置',
						callback: result => {
							if (result) {
								uni.openSetting({

								})
							}
						}
					})
				} else {
					that.$toast.alert({
						content: res.errMsg,
						callback: result => {

						}
					})
				}
			}
		})
	},
	getCurrentCity(lat, lon) { //获取城市name和id
		let that = this
		that.$httpRequest.get({
			that: that,
			url: 'wechat/positionToCityTencent',
			params: {
				"lal": lat + ',' + lon
			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.formData.address = res.data.cityName + res.data.countyName

				} else {
					that.$toast.alert({
						content: res.message,
						callback: result => {

						}
					})
				}
			}
		})
	},
	//获取所以话题
	getAllTopic() {
		let that = this
		that.$httpRequest.get({
			that,
			url: 'wechat/getAllTopic',
			params: {},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.topic = res.data
				} else {
					that.$toast.alert({
						content: res.message,
						callback: result => {
							if (result.confirm) {
								uni.navigateBack({
									delta: 1
								})
							}
						}
					})
				}
			}
		})
	},
	//新增话题
	addTopic() {
		let that = this
		that.$httpRequest.request({
			that,
			url: 'wechat/addTopic',
			params: {
				name: that.topic_title
			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.closePop()
					// that.getAllTopic()
					that.topicList.push(res.data.id)
					that.topic.unshift({
						'id': res.data.id,
						'name': res.data.name
					})
					that.formData.topics = that.topicList.join(',')
					that.topic_title = ''
					that.$toast.msg(res.message, {
						icon: 1
					})
				} else {
					that.$toast.alert({
						content: res.message,
						callback: result => {
							if (result.confirm) {
								uni.navigateBack({
									delta: 1
								})
							}
						}
					})
				}
			}
		})
	},
	delTag(item, index) {
		let that = this
		that.$toast.confirm({
			content: `是否删除${item.name}？`,
			confirmText: '删除',
			callback: result => {
				if (result) {
					that.$httpRequest.request({
						that,
						url: 'wechat/deleteTopic',
						method: 'get',
						params: {
							id: item.id
						},
						success: res => {
							if (res.code === that.$httpConfig.SUCCESS_CODE) {
								if (that.topicList.includes(item.id)) {
									that.topicList = that.topicList.filter(function(ele) {
										return ele != item.id;
									});
								}
								that.formData.topics = that.topicList.join(',')
								that.getAllTopic();
							} else {
								that.$toast.alert({
									content: res.message,
									callback: result => {
										if (result.confirm) {
											uni.navigateBack({
												delta: 1
											})
										}
									}
								})
							}
						}
					}, false)
				}
			}
		})

	},
	//选择话题
	chooseTopic(item) {
		if (this.topicList.includes(item.id)) {
			//includes()方法判断是否包含某一元素,返回true或false表示是否包含元素，对NaN一样有效
			//filter()方法用于把Array的某些元素过滤掉，filter()把传入的函数依次作用于每个元素，然后根据返回值是true还是false决定保留还是丢弃该元素：生成新的数组
			this.topicList = this.topicList.filter(function(ele) {
				return ele != item.id;
			});
		} else {
			this.topicList.push(item.id);

		}
		this.formData.topics = this.topicList.join(',')
		// console.log(this.formData.topics)
		wx.vibrateShort()
	},
	setTopic() {
		this.$refs.topic.open()
	},
	closePop() {
		this.$refs.topic.close()
	},
	//发布草稿
	toDraft() {
		this.formData.draft = true
		this.submit()
	},
	sendInfo() {
		this.formData.draft = false
		this.submit()
	},
	submit() {
		let that = this
		// 请求前
		uni.showLoading({
			title: "上传中",
			mask: true //是否显示透明蒙层，防止触摸穿透，默认：false
		});
		if (this.imageList.length < 1) {
			this.$toast.msg('请上传照片或视频', {
				icon: 1
			})
			uni.hideLoading();
			return false
		}
		let params = {}
		params = this.formData;
		if (this.mentionedFriends.length > 0) {
			params.visibilityUsers = this.mentionedFriends.map(item => {
				return item.id
			}).join(',')
		}
		// if (this.id) this.formData.draft = false;
		const sortDate = this.reSort();
		var newlist = sortDate.map((item, index) => {
			if (item) {
				return item = item.id
			}
		})
		that.formData.files = newlist.join(',')
		that.loading = true
		that.$httpRequest.request({
			that: that,
			url: that.id ? 'wechat/editInformation' : that.type == 1 ? 'wechat/shareGoods' :
				'wechat/publishInformation',
			params: params,
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.orderId = res.data
					that.upRefreshFlag(true) //刷新
					that.$toast.msg(that.formData.draft ? '保存成功' : '发布成功', {
						icon: 1
					})


					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 300)
					// that.wechatPay()

				} else {
					that.$toast.alert({
						content: res.message,
						callback: result => {
							if (result.confirm) {

							}
						}
					})
				}
			}
		})
		setTimeout(() => { //延时指定时间后，再解冻
			that.loading = false;
		}, 1000);
	},
	wechatPay() {
		let that = this

		// if (that.loading) {
		// 	that.$toast.msg('请求中...', {
		// 		icon: 1
		// 	})
		// 	return false
		// }
		that.loading = true
		uni.requestSubscribeMessage({
			tmplIds: ['Vc2tzjTdqB3dBLxTOwgJsECSpSeh20rtdCKfelFCnfY'],
			success(res) {
				let url = 'wechat/orderPay'
				that.$httpRequest.request({
					that: that,
					url,
					params: {
						id: that.orderId
					},
					success: res => {
						that.loading = false
						if (res.code === that.$httpConfig.SUCCESS_CODE) {
							// that.upSuccessPay(true)
							let data = res.data
							uni.requestPayment({
								timeStamp: data.timeStamp,
								nonceStr: data.nonceStr,
								package: data.package,
								signType: data.signType,
								paySign: data.paySign,
								success: res => {
									that.$toast.alert({
										content: '支付成功,发布完成！',
										callback: result => {
											if (result.confirm) {
												uni.navigateBack({
													delta: 1
												})
											}
										}
									})
								}
							})
						} else {
							that.$toast.alert({
								content: res.msg,
								callback: result => {

								}
							})
						}
					}
				})
			}
		});

	},
	// 打开picker
	openDatetimePicker() {
		this.$refs.myPicker.show();
	},

	// 关闭picker
	closeDatetimePicker() {
		this.$refs.myPicker.hide();
	},

	handleSubmit(e) {

		// {year: "2023", month: "07", day: "11", hour: "15", minute: "21", seconds: '55'}
		this.birthday = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}`;
		this.formData.scheduleTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:00`;
		// console.log("初始化时间", e);
	},
	toMap() {
		let that = this
		wx.chooseLocation({
			success(res) {
				// {
				// 	address:'具体地址',
				// 	latitude:'',
				// 	longitude:'',
				// 	name:'地名'
				// }
				console.log(res, '成功回调')

				if (res.address) {
					that.formData.address = res.name + ' (' + res.address + ')'
				} else {
					that.formData.address = res.name
				}
				that.formData.lal = res.latitude + ',' + res.longitude
			},
			fail(res) {
				console.log(res, '失败回调')
			},
			complete(res) {
				console.log(res, '结束回调')
			}
		})
	},

	//拖拽
	onChange(e, item) {
		if (!item) return
		item.oldX = e.detail.x
		item.oldY = e.detail.y
		if (e.detail.source === 'touch') {
			if (item.moveEnd) {
				item.offset = Math.sqrt(Math.pow(item.oldX - item.absX * this.viewWidth, 2) + Math.pow(item.oldY - item
					.absY * this.viewWidth, 2))
			}
			let x = Math.floor((e.detail.x + this.viewWidth / 2) / this.viewWidth)
			if (x >= this.colsValue) return
			let y = Math.floor((e.detail.y + this.viewWidth / 2) / this.viewWidth)
			let index = this.colsValue * y + x
			if (item.index != index && index < this.imageList.length) {
				this.changeStatus = false
				for (let obj of this.imageList) {
					if (item.index > index && obj.index >= index && obj.index < item.index) {
						this.change(obj, 1)
					} else if (item.index < index && obj.index <= index && obj.index > item.index) {
						this.change(obj, -1)
					} else if (obj.id != item.id) {
						obj.offset = 0
						obj.x = obj.oldX
						obj.y = obj.oldY
						setTimeout(() => {
							this.$nextTick(() => {
								obj.x = obj.absX * this.viewWidth
								obj.y = obj.absY * this.viewWidth
							})
						}, 0)
					}
				}
				item.index = index
				item.absX = x
				item.absY = y
			}
		}
	},
	change(obj, i) {
		obj.index += i
		obj.offset = 0
		obj.x = obj.oldX
		obj.y = obj.oldY
		obj.absX = obj.index % this.colsValue
		obj.absY = Math.floor(obj.index / this.colsValue)
		setTimeout(() => {
			this.$nextTick(() => {
				obj.x = obj.absX * this.viewWidth
				obj.y = obj.absY * this.viewWidth
			})
		}, 0)
	},
	touchstart(item) {
		this.imageList.forEach(v => {
			v.zIndex = 'auto'
		})
		item.zIndex = 99
		item.moveEnd = true
		this.tempItem = item
		this.timer = setTimeout(() => {
			item.scale = this.scale
			item.opacity = this.opacity
			clearTimeout(this.timer)
			this.timer = null
		}, 200)
	},
	touchend(item) {
		item.scale = 1
		item.opacity = 1
		item.x = item.oldX
		item.y = item.oldY
		item.offset = 0
		item.moveEnd = false
		setTimeout(() => {
			this.$nextTick(() => {
				item.x = item.absX * this.viewWidth
				item.y = item.absY * this.viewWidth
				this.tempItem = null
				this.changeStatus = true
			})
		}, 0)
	},
	mouseenter() {
		//#ifdef H5
		this.imageList.forEach(v => {
			v.disable = false
		})
		//#endif

	},
	mouseleave() {
		//#ifdef H5
		if (this.tempItem) {
			this.imageList.forEach(v => {
				v.disable = true
				v.zIndex = v.index + 9
				v.offset = 0
				v.moveEnd = false
				if (v.id == this.tempItem.id) {
					if (this.timer) {
						clearTimeout(this.timer)
						this.timer = null
					}
					v.scale = 1
					v.opacity = 1
					v.x = v.oldX
					v.y = v.oldY
					this.$nextTick(() => {
						v.x = v.absX * this.viewWidth
						v.y = v.absY * this.viewWidth
						this.tempItem = null
					})
				}
			})
			this.changeStatus = true
		}
		//#endif
	},
	addImages() {
		let that = this;
		let tempObj = {}
		if (this.imageList.length > 15) {
			this.$toast.msg('最多数量为15', {
				icon: 1
			})
			return false
		}
		uni.showActionSheet({
			itemList: ['照片', '视频'],
			success: function(res) {
				if (res.tapIndex == 0) {
					//上传照片
					that.tempFileList = [];
					that.$httpRequest.handlerUploadPic(res => {
						if (res.code === that.$httpConfig.SUCCESS_CODE) {
							// console.log(res, "完成上传")
							res.tempNameArray.forEach((item, index) => {
								if (item.indexOf(res.data
										.fileOriginName) > 0) {
									tempObj[index] = res.data
								}
								// #ifdef  H5
								tempObj[index] = res.data
								// #endif

							})
							//多照片
							var arr = []
							for (let key in tempObj) {
								arr.push(tempObj[key])

							}
							that.tempFileList = that.tempFileList.concat(arr)
							that.tempFileList = that.unique(that.tempFileList)
							that.tempFileList = that.trimSpace(that.tempFileList)
							that.tempFileList.forEach((item) => {
								that.addProperties(item)
							})
						}
					});
				} else {
					//上传视频
					that.$httpRequest.handlerUploadVideo(res => {
						if (res.code === that.$httpConfig.SUCCESS_CODE) {
							that.addProperties(res.data)
						}

					})

				}
				console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
			},
			fail: function(res) {
				console.log(res.errMsg);
			}
		});
	},
	reSort() {
		const sortedDesc = this.imageList.slice().sort((a, b) => a.index - b.index);
		return sortedDesc
	},
	delImageMp(item, index) {
		this.imageList.splice(index, 1)
		for (let obj of this.imageList) {
			if (obj.index > item.index) {
				obj.index -= 1
				obj.x = obj.oldX
				obj.y = obj.oldY
				obj.absX = obj.index % this.colsValue
				obj.absY = Math.floor(obj.index / this.colsValue)
				this.$nextTick(() => {
					obj.x = obj.absX * this.viewWidth
					obj.y = obj.absY * this.viewWidth
				})
			}
		}
		this.add.x = (this.imageList.length % this.colsValue) * this.viewWidth + 'px'
		this.add.y = Math.floor(this.imageList.length / this.colsValue) * this.viewWidth + 'px'
	},
	addProperties(item, status) {
		if (this.imageList.some(img => img.id === item.id)) {
			return; // 找到了 id 为 1 的对象，执行 return
		}
		if (status === undefined) {
			status = 0
		}
		let absX = this.imageList.length % this.colsValue
		let absY = Math.floor(this.imageList.length / this.colsValue)
		let x = absX * this.viewWidth
		let y = absY * this.viewWidth
		this.imageList.push({
			filePath: item.filePath,
			fileSuffix: item.fileSuffix,
			id: item.id,
			status: status,
			x,
			y,
			oldX: x,
			oldY: y,
			absX,
			absY,
			scale: 1,
			zIndex: 9,
			opacity: 1,
			index: this.imageList.length,
			disable: false,
			offset: 0,
			moveEnd: false
		})
		this.add.x = (this.imageList.length % this.colsValue) * this.viewWidth + 'px'
		this.add.y = Math.floor(this.imageList.length / this.colsValue) * this.viewWidth + 'px'
	},
	nothing() {},
	rpx2px(v) {
		return this.width * v / 750
	},
}